package cn.smbms.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.sun.istack.internal.logging.Logger;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.user.UserService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;
import cn.smbms.tools.ResponseResult;
import cn.smbms.tools.ResultCode;


@Controller
@RequestMapping("/user")
public class UserController {
	
	Logger logger = Logger.getLogger(UserController.class);
	
	@Resource
	private UserService userService;
	
	//登录
	@RequestMapping(value="/login")
	@ResponseBody
	public String doLogin(@RequestParam String userCode,
						  @RequestParam String userPassword,
						 HttpSession session)throws Exception{
		//调用service方法，进行用户匹配
		User user = userService.login(userCode, userPassword);
		
		//封装数据返回前端
		Map<String,Object> map = new HashMap<String, Object>();
		if(user != null){ //登录成功
			session.setAttribute(Constants.USER_SESSION,user);
			map.put("success",true);
		}else{
			map.put("success",false);
		}
		return JSON.toJSONString(map);
	}
	
	//退出
	@RequestMapping(value="/logout")
	public String logout(HttpSession session){
		session.removeAttribute(Constants.USER_SESSION);
		return "login";
	}
	
	//分页查询用户列表
	@RequestMapping("/userlist")
	@ResponseBody
	public String getUserList(@RequestParam(required=false)String userName,
								@RequestParam(required=false)Integer page,
								HttpSession session) throws Exception{
		
		logger.info("====================="+userName);
		//logger.info("====================="+page.toString());
		User user = (User) session.getAttribute(Constants.USER_SESSION);
		//判断用户是否登录
		/*if(user == null){
			return ResponseResult.failed(ResultCode.ERROR_700.code(), ResultCode.ERROR_700.message());
		}*/
		int pageSize = Constants.pageSize;  //页容量
		
		//总数量
		int totalCount = userService.getUserCount(userName);
		
		//控制首页
		if(page == null || page < 1){
			page = 1;
		}
		
		PageSupport<User> pageSupport=new PageSupport<User>();
		pageSupport.setCurrentPageNo(page);
		pageSupport.setPageSize(pageSize);
		pageSupport.setTotalCount(totalCount);
		//总页数
		int totalPageCount =pageSupport.getTotalPageCount();
		//控制尾页
		if(page > totalPageCount){ 
			page = totalPageCount;
		}
		int currentPageNo = page; //当前页码
		currentPageNo = (currentPageNo-1)*pageSize;
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("userName", userName);
		map.put("currentPageNo",currentPageNo);
		map.put("pageSize",pageSize);
		//调用service层获取数据
		List<User> userList=userService.getUserListByPages(map);
		
		//封装数据返回前端
		Map<String,Object> map2 = new HashMap<String, Object>();
		map2.put("code",0);
		map2.put("success",true);
		map2.put("page",page );
		map2.put("pageSize", pageSize);
		map2.put("count", totalCount);
		map2.put("data",userList);
		map2.put("msg","数据查询成功");
		return JSON.toJSONString(map2);
	}

	
	//增加用户
	@ResponseBody
	@RequestMapping(value="/useraddsave",method=RequestMethod.POST)
	public Object addUserSave(User user,HttpSession session,HttpServletRequest request,
								@RequestParam(value="attach",required=false) MultipartFile [] attachs) throws Exception{
	
		User user2 = (User) session.getAttribute(Constants.USER_SESSION);
		//判断用户是否登录
		if(user2 == null){
			return ResponseResult.failed(ResultCode.ERROR_700.code(), ResultCode.ERROR_700.message());
		}
		if(attachs != null){
		for (int i = 0; i < attachs.length; i++) {
			String errorInfo = null;
			MultipartFile attach = attachs[i];
			//判断文件是否为空
			if(!attach.isEmpty()){
				if(i == 0){
					errorInfo = "头像上传失败！";
				}else{
					errorInfo = "工作照上传失败！";
				}
				
				String oldFileName = attach.getOriginalFilename(); //原文件名
				logger.info("oldFileName--------------"+oldFileName);
				String prefix = FilenameUtils.getExtension(oldFileName); //原文件后缀
				logger.info("prefix--------------"+prefix);
				int filesize = 5000000;
				logger.info("filesize--------------"+filesize);
				if(attach.getSize() > filesize){ //文件上传大小不得超过500KB
					request.setAttribute(errorInfo,"*上传文件大小不得超过500KB");
					return "useradd";
				}else if(prefix.equalsIgnoreCase("jpg")
						 || prefix.equalsIgnoreCase("png")
						 || prefix.equalsIgnoreCase("jpeg")
						 || prefix.equalsIgnoreCase("pneg")){ //上传图片格式正确
					String fileName = "";
					String path = "";
					if(i == 0){
						fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";
						path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadPersonImgfiles");
					}else{
						fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_work.jpg";
						path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadWorkfiles");
					}
					
					logger.info("fileName--------------"+fileName);
					File targetFile = new File(path,fileName);
					if(!targetFile.exists()){
						//创建路径
						targetFile.mkdirs();
					}
					//保存
					try {
						attach.transferTo(targetFile);
					} catch (Exception e) {
						e.printStackTrace();
						return ResponseResult.failed("上传图片失败");
					}
					if(i == 0){
						user.setPicPath(fileName);
					}else{
						user.setWorkPicPath(fileName);
					}
					
				}else{
					return ResponseResult.failed("*上传图片格式不正确");
				}
			}
		}
	}
		user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
		user.setCreationDate(new Date());
		
		if(userService.add(user)>0){
			return ResponseResult.ok("用户添加成功！");
		}else{
			return ResponseResult.failed(ResultCode.ERROR_SQL_ERROR.code(),ResultCode.ERROR_SQL_ERROR.message());
		}
		
		
	}

	//修改
	@RequestMapping(value="/usermodifysave")
	@ResponseBody
	public Object modifyUserSave(User user,HttpSession session) throws NumberFormatException, Exception{
		User user2 = (User) session.getAttribute(Constants.USER_SESSION);
		//判断用户是否登录
		if(user2 == null){
			return ResponseResult.failed(ResultCode.ERROR_700.code(), ResultCode.ERROR_700.message());
		}
		user.setModifyBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
		user.setModifyDate(new Date());
		logger.info("userid-------------"+user.getId());
		if(userService.modify(user)>0){
			return ResponseResult.ok("修改成功");
		}else{
			return ResponseResult.failed("修改失败");
		}
	}
	
	//查看
	@RequestMapping(value="/view")
	@ResponseBody
	public Object view(@RequestParam(required=false) String id,
						HttpSession session) throws NumberFormatException, Exception{
		User user2 = (User) session.getAttribute(Constants.USER_SESSION);
		//判断用户是否登录
		if(user2 == null){
			return ResponseResult.failed(ResultCode.ERROR_700.code(), ResultCode.ERROR_700.message());
		}
		User user = null;
		if(id != null && !id.equals("")){
			user = userService.getUserById(Integer.parseInt(id));
		}
		return ResponseResult.ok(user);
	}
	
	//删除
	@RequestMapping(value="/delete")
	@ResponseBody
	public Object delete(@RequestParam(required=false) String id,
							HttpSession session) throws Exception{
		User user2 = (User) session.getAttribute(Constants.USER_SESSION);
		//判断用户是否登录
		if(user2 == null){
			return ResponseResult.failed(ResultCode.ERROR_700.code(), ResultCode.ERROR_700.message());
		}
		Integer _id = null;
		if(id != null && !id.equals("")){
			_id = Integer.parseInt(id);
		}
		if(userService.deleteUserById(_id)>0){
			return ResponseResult.ok("删除用户成功");
		}else{
			return ResponseResult.failed("删除用户失败");
		}
		
	}
}
